using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace WineCellar.Web.Controllers
{
    public class LoginController :Controller
    {        
        public ActionResult Index()
        {
            if (HttpContext.Request.RequestType == "GET") return View();

            var userName = HttpContext.Request["UserName"];
            var password = HttpContext.Request["Password"];

            if (string.IsNullOrEmpty(userName))
            {
                ViewData["ErrorMessage"] = "Please enter your user name.";
                return View();
            }

            if (Membership.ValidateUser(userName, password))
            {
                FormsAuthentication.SetAuthCookie(userName, true);
                var returnUrl = HttpContext.Request["ReturnUrl"];
                if (string.IsNullOrEmpty(returnUrl))
                {
                    return RedirectToAction("Index", "Home");
                }
                var stringArray = returnUrl.Split("/".ToCharArray());
                if (stringArray.Length >= 4)
                {
                    var action = stringArray[3];
                    var controller = stringArray[2];
                    return RedirectToAction(action, controller);
                }
                return RedirectToAction("Index", "Home");
            }

            ViewData["UserName"] = userName;
            ViewData["ErrorMessage"] = "Incorrect credentials, please try again.";

            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }
    }
}